<!DOCTYPE html>
<html>
    <head>
        <link rel="stylesheet" href="./resources/style.css">
        <script type="module">
            import { 
                log,
                logToId,
                clearId,
                randomId,
                stringify,
                currentNetwork,
                disconnectHandler
            } from './resources/utils.js';

            // import WASM32 SDK
            import * as kaspa from '../../web/kaspa-rpc/kaspa.js';
            let { Resolver, RpcClient, Encoding } = kaspa;

            (async () => {
                // load WASM32 SDK binaries 
                await kaspa.default('../../web/kaspa-rpc/kaspa_bg.wasm');

                let networkId = currentNetwork();
                log(`Connecting to Kaspa network...`);
                log(`Selected network is ${networkId.class("network")}...`);

                const rpc = new RpcClient({
                    resolver : new Resolver(),
                    networkId,
                });

                let id;
                rpc.addEventListener("connect", async (event) => {
                    clearId(id);
                    id = randomId();

                    log("Connected to", rpc.url.class("network"));
                    log("Subscribing to Block Added...");
                    await rpc.subscribeBlockAdded();
                });
                
                rpc.addEventListener("disconnect", async (event) => {
                    log("Disconnected from", rpc.url.class("network"));
                    console.log("Disconnect",event);
                });

                rpc.addEventListener("block-added", async (event) => {
                    // remove parentsByLevel from header (reduce data output)
                    delete event.data.block.header.parentsByLevel;
                    logToId(id, event);
                });


                log("Connecting to public node...");
                await rpc.connect();

                disconnectHandler(rpc);
            })();

        </script>
    </head>
    <body></body>
</html>